//
//  MyPostListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/11.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "PostListHeaderView.h"
#import "TT_BaseNaviView.h"
#import "PostEvaluateCell.h"
#import "PostEvaluateLookMoreCell.h"
#import "PostPublishViewController.h"
#import "MyPostSectionHeaderView.h"
#import "PostDetailViewController.h"
#import "MyPostListViewController.h"

@interface MyPostListViewController ()<UITableViewDelegate, UITableViewDataSource>


@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) NSMutableArray <CommonPostModel*>* dataArray;

@property (nonatomic, strong) UIButton *addBtn;

@end

@implementation MyPostListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];

}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshParam];
    [self request_postList];
}

- (void)initView {
    
    self.title = @"我的帖子";
    
    if([self.tableview respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.view addSubview:self.addBtn];
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-100);
        make.right.mas_equalTo(-5);
        make.height.width.mas_equalTo(68);
    }];
    
    [self initViewAction];
}

- (void)initViewAction {

}

- (void)addPostAction {
    
    PostPublishViewController *vc = [[PostPublishViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
    
#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    CGFloat height = [MyPostSectionHeaderView calculateHWithModel:self.dataArray[section]];
    return height;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MyPostSectionHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"MyPostSectionHeaderView" owner:nil options:nil].firstObject;
    
    WEAKSELF
    sectionHeader.MYPostSectionHeaderViewBlock = ^(MYPostSectionHeaderActionType type, NSInteger index) {
      
        switch (type) {
            case MYPostSectionHeaderActionType_image:{
            } break;
            case MYPostSectionHeaderActionType_del:{
                [TT_Alert alert:@"是否确定删除该帖子？" cancleBtnTitle:@"取消" cancleAction:^{
                } doneBtnTitle:@"确认" doneAction:^{
                    [weakSelf request_updatePostListWithIndex:section];
                }];
            } break;

            default:
                break;
        }
        
    };
    
    [sectionHeader fillWithModel:self.dataArray[section]];
    
    [sectionHeader addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        PostDetailViewController *vc = [[PostDetailViewController alloc] init];
        vc.pid = weakSelf.dataArray[section].pid;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    return sectionHeader;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row <2) {
        PostEvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostEvaluateCellID"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        [cell fillWithModel:self.dataArray[indexPath.section].sysPostChildList[indexPath.row]];
        
        return cell;
    } else {
        PostEvaluateLookMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostEvaluateLookMoreCellID"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        
        cell.mainTitleLab.text = [NSString stringWithFormat:@"查看共%ld条评论",self.dataArray[indexPath.section].sysPostChildList.count];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row <2) {

    } else {

        PostDetailViewController *vc = [[PostDetailViewController alloc] init];
        vc.pid = self.dataArray[indexPath.section].pid;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn setImage:[UIImage imageNamed:@"add_post"] forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(addPostAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf1f1f1);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostEvaluateCell" bundle:nil] forCellReuseIdentifier:@"PostEvaluateCellID"];
        
        [_tableview registerNib:[UINib nibWithNibName:@"PostEvaluateLookMoreCell" bundle:nil] forCellReuseIdentifier:@"PostEvaluateLookMoreCellID"];

        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_postList];
        }];
        
        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_postList];
        }];
        
    }
    return _tableview;
}

- (void)request_postList {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    [t setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];

    [t setValue:@"2" forKey:@"isDel"];
    [t setValue:@"1" forKey:@"type"];
    [t setValue:@"2" forKey:@"remark"];
    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SysPosts];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        
                        if (weakSelf.pageNum == 1) {
                            weakSelf.dataArray = @[].mutableCopy;
                            
                            if (list.count == 0) {
                                [[TTNoResultManager shareManager] showNoResultWithStateInView:weakSelf.tableview errorCode:kTTViewState_EmptyView btnTitle:@"" didPressButton:^{
                                }];
                            }
                        }
                            
                        for (NSDictionary *dic in list) {
                            CommonPostModel *model = [CommonPostModel modelWithDictionary:dic];
                            model.content = [NSString stringWithFormat:@"【%@】%@",model.themeTitle,model.title];
                            model.textHeight = [Utilities getStringHeightWithText:model.content font:[UIFont systemFontOfSize:14] viewWidth:(TTScreenWidth - 28)];
                            
                            if (model.sysMediaList.count > 0) {
                                model.imageHeight = (TTScreenWidth - 32)/3 + 10;
                            } else {
                                model.imageHeight = CGFLOAT_MIN;
                            }
                            
                            NSArray *sysMediaList = [dic valueForKey:@"sysMediaList"];
                            if ([sysMediaList isKindOfClass:[NSArray class]]) {
                                model.sysMediaList = @[].mutableCopy;
                                model.photoArray = @[].mutableCopy;
                                for (id mediaDic in sysMediaList) {
                                    
                                    CommonMediaModel *mediaModel = [[CommonMediaModel alloc] init];
                                    if ([mediaDic isKindOfClass:[NSDictionary class]]) {
                                        NSDictionary *media = mediaDic;
                                        mediaModel = [CommonMediaModel modelWithDictionary:media];
                                        [model.photoArray addObject:mediaModel.url];

                                    }
                                    
                                    if ([mediaDic isKindOfClass:[NSString class]]) {
                                        NSString *media = mediaDic;
                                        mediaModel.url = media;
                                        [model.photoArray addObject:media];
                                    }
                                    
                                    [model.sysMediaList addObject:mediaModel];
                                }
                            }
                            
                            NSArray *sysPostChildList = [dic valueForKey:@"sysPostChildList"];
                            if ([sysPostChildList isKindOfClass:[NSArray class]]) {
                                model.sysPostChildList = @[].mutableCopy;
                                for (NSDictionary * evaDic in sysPostChildList) {
                                    CommunityEvaModel *evaModel = [CommunityEvaModel modelWithDictionary:evaDic];
                                    [model.sysPostChildList addObject:evaModel];
                                }
                            }
                            
                            [weakSelf.dataArray addObject:model];
                        }
                            
                        
                    } else {
                        
                    }
                    [weakSelf.tableview reloadData];
                }
            }
        }

        
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}

//API_UpdateSysPosts
- (void)request_updatePostListWithIndex:(NSInteger)index {
        
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:self.dataArray[index].pid forKey:@"pid"];
    [dic setValue:@"1" forKey:@"isDel"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_UpdateSysPosts];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                [weakSelf request_postList];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}


@end
